package cn.diancan.action; 

import java.io.File;
import java.util.Collection;
import java.util.Map;  
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.diancan.util.RequestUtil;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.diancan.exception.OutMsgCode;
import cn.diancan.exception.OutMsgException;
import cn.diancan.model.types.PfAndDevice;
import cn.diancan.util.ResponseJSONUtil;

/**
 * 基础ACTION,其他ACTION继承此ACTION来获得writeJson和ActionSupport的功能
 */ 
public class BaseAction extends BaseServiceImplAction {



	private static final Logger logger = Logger.getLogger(BaseAction.class); 

	protected final static String RESULT_URL="url";
	protected final static String RESULT_FREEMARK="freemark"; 
	protected final static String RESULT_URL_REDIRECT="url_redirect"; 
	  
	private String dynamicUrl="index"; 
	
	public String getDynamicUrl() {
		return dynamicUrl;
	}

 	public void setDynamicUrl(String dynamicUrl) {
		this.dynamicUrl = dynamicUrl;
	}

	/**
	 * jsp 页面
	 * @param dynamicUrl
	 * @return
	 */
	public String jspView(String dynamicUrl){
		setDynamicUrl(dynamicUrl);
		return RESULT_URL;
	}

	/**
	 * ftl 页面
	 * @param dynamicUrl
	 * @return
	 */
	public String freemarkView(String dynamicUrl){
		setDynamicUrl(dynamicUrl);
		return RESULT_FREEMARK;
	}
	/**
	 * 跳转
	 * @param dynamicUrl
	 * @return
	 */
	public String redirect(String dynamicUrl){
		if(dynamicUrl.startsWith("/")){
			dynamicUrl =  getBasePath( )+ dynamicUrl.substring(1);
		}

		setDynamicUrl(dynamicUrl);
		return RESULT_URL_REDIRECT;
	}


	/**
	 * 返回request
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	protected HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}
	
	protected Map<String,Object> getMapSession(){
		return ServletActionContext.getContext().getSession();
	}
	
	protected ServletContext getApplication(){

		return ServletActionContext.getServletContext();
		}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	protected String getIpAddr() {
		String ip = getRequest().getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRequest().getRemoteAddr();
		}
		return ip;
	}

/*	protected void getSubAuths(String psign) {
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext
				.getRequest().getSession().getAttribute(
						ResourceUtil.getSessionInfoName());
		if (sessionInfo.getLoginName().equals("admin")) {
			auths = "all";
		} else {
			vResource = new VResource();
			vResource.setRid(Long.parseLong(sessionInfo.getRoleIds()));
			vResource.setSign(psign);
			List<VResource> list = resourceServiceI.getSubResources(vResource);
			auths = "";
			if (list != null) {
				for (VResource vResource : list) {
					auths += vResource.getSign() + ",";
				}
			}
		}
	}*/

	 
	
	public String getBasePath(){
		String path = getRequest().getContextPath(); 
		String basePath =getRequest().getScheme()+"://"+getRequest().getServerName();
		if(80==getRequest().getServerPort()){
			basePath=getRequest().getScheme()+"://"+getRequest().getServerName()+path+"/";
		}else{
			basePath =getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path+"/";
		} 
		return basePath;
	}
	
	/**
	 * 只有不管端口
	 * @return
	 */
	public String getBasePath2(){
		String path = getRequest().getContextPath();  
		return getRequest().getScheme()+"://"+getRequest().getServerName()+path+"/";
	}
	 
	/**
	 * 链接来源
	 * @return
	 */
	//public String get
	public String getSrcReferer(){
		String referer = getRequest().getHeader("referer");
		if(null==referer){
			referer = getRequest().getHeader("Referer");
			if(null==referer){
				return "";
			}
		}
		return referer;
	}
	
	/**
	 * 根据cookiekey 获取Cookie
	 * @param request
	 * @param cookie_key
	 * @return
	 */
	public Cookie getCookieByName(String cookie_key){ 
		Cookie[] cookies = getRequest().getCookies();//这样便可以获取一个cookie数组   
		if(null!=cookies){
			for(int i=0 ;i<cookies.length;i++){
				Cookie cookie =cookies[i];
				//System.out.println(cookie.getName());
			    //System.out.println(cookie.getValue());  
				if(null!= cookie.getName() && cookie_key.equals(cookie.getName())){
					return cookie;
				} 
			}
		}
		return null;
	}
	
	/**
	 * 设置请求属性
	 * 
	 * @param key
	 * @param value
	 */
	public void put(String key, Object value)
	{
		getRequest().setAttribute(key, value);
	}
	/**
	 * 后台错误页面
	 * @param message
	 * @return
	 */
	public String managerError(String message){
		put("message",message);
		setDynamicUrl("/views/ftl/manager/error.ftl");
		return RESULT_FREEMARK;
	}
	/**
	 * 前台用户中心错误页面
	 * @param message
	 * @return
	 */
	public String memberError(String message){
		put("message",message);
		setDynamicUrl("/views/ftl/member/error.ftl");
		return RESULT_FREEMARK;
	}
	
	/**
	 * 手机端错误页面
	 * @param message
	 * @return
	 */
	public String mobileError(String message){
		put("message",message);
		setDynamicUrl("/views/ftl/mobile/error.ftl");
		return RESULT_FREEMARK;
	}
	
	
	
	/**
	 * json  格式(简化返回) 
	 * <p>
	 * 如果是boolean  true 会返回 successMsg 反之 failMsg 
	 * </p>
	 * @param data 
	 * @return
	 */
	public String jsonFormat(Object data){
	    return jsonFormat(data, "success","error");
	}
	
	/**
	 * json  格式(简化返回) 
	 * <p>
	 * 如果是boolean  true 会返回 successMsg 反之 failMsg 
	 * </p>
	 * @param data
	 * @param successMsg 
	 * @return
	 */
	public String jsonFormat(Object data,String successMsg){
	    return jsonFormat(data, successMsg,"error");
	}
	
	/**
	 * json 格式(简化返回)
	 * <p>
	 * 如果是boolean  true 会返回 successMsg 反之 failMsg 
	 * </p>
	 * @param data
	 * @param successMsg
	 * @param failMsg
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public String jsonFormat(Object data,String successMsg,String failMsg){ 
	    if(data instanceof Boolean  ){
		if( (Boolean)data){
		    return ResponseJSONUtil.commonJson(OutMsgCode.SUCCESS.getCode(), successMsg);
		}
		return ResponseJSONUtil.commonJson(OutMsgCode.ERROR.getCode(), failMsg);
	    } 
	    if(null == data ){
		return ResponseJSONUtil.commonJson(OutMsgCode.NOTDATA.getCode(), "NOT DATA");
	    }
	    
	    if(data instanceof String){ 
		return ResponseJSONUtil.commonJson(OutMsgCode.SUCCESS.getCode(), successMsg,(String)data);
	    }if(data instanceof Collection){  
		Collection collection = (Collection)data;
		if(collection.size()<=0){
		    return ResponseJSONUtil.commonJson(OutMsgCode.NOTDATA.getCode(), "NOT DATA");
		} 
	    } else if(data instanceof Map){
		Map map= (Map)data;
		if(map.size()<=0){
		    return ResponseJSONUtil.commonJson(OutMsgCode.NOTDATA.getCode(), "NOT DATA");
		}
	    } 
	    return ResponseJSONUtil.commonJson(OutMsgCode.SUCCESS.getCode(), successMsg,data);
	} 
	
	
	/**
	 * json 错误 
	 * @param errorMsg
	 * @return
	 */
	public String jsonError(String errorMsg){ 
	    return ResponseJSONUtil.commonJson(OutMsgCode.ERROR.getCode(), errorMsg);
	}
	
	/**
	 * 异常错误直接处理..
	 * @param e
	 * @return
	 */
	public String jsonError(Exception e){
	    if(e instanceof OutMsgException){
		OutMsgException outException =(OutMsgException) e;
		return ResponseJSONUtil.commonJson(outException.getCode(), outException.getMessage());
	    }
	    e.printStackTrace();
	    return ResponseJSONUtil.commonJson(OutMsgCode.ERROR.getCode(), "系统繁忙");
	} 
	
	 
	
	/**
	 * json 成功信息
	 * @param successMsg
	 * @return
	 */
	public String jsonSuccess(String successMsg){
	    return ResponseJSONUtil.commonJson(OutMsgCode.SUCCESS.getCode(), successMsg);
	} 
	
	/**
	 * 直接返回文本(例 : json 或 html)
	 * @param html
	 * @return
	 */
	public String textString(String html){
	    return ResponseJSONUtil.textString(html);
	}
	
	
    /**
     * 错误返回 DeviceAndPf.Unkown
     * @return
     */
    protected PfAndDevice getPfDevice() {
	try {
	    String pfDevice = getRequest().getParameter("pfDevice");
	    return  PfAndDevice.getPfAndDevice(pfDevice); 
	} catch (Exception e) { 
	    e.printStackTrace();
	}
	return PfAndDevice.Unkown;
    }

    /**
     * 错误返回  0.1 最小的版本号
     * @return
     */
    protected float getPfAppVersion() {
	try {
	    Float pfAppVersion = Float.valueOf(getRequest().getParameter("pfAppVersion"));
	    return pfAppVersion;
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return 0.1f;
    }
	
	
	
}
